// 导入一个接口
import { loginAPI } from '@/api/user'
// 导入一个插件得方法  存token得插件
import { getToken, setToken, removeToken } from '@/utils/auth'
// 导入路由
// import { resetRouter } from '@/router'
// state存放
const getDefaultState = () => {
  return {
    // token
    token: getToken() || ''
    // name: '',
    // avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 设置token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 获取token
  async login({ commit }, data) {
    const res = await loginAPI(data)
    // console.log(res)
    commit('SET_TOKEN', res.token)
    setToken(res.token)
    return res
  },
  // get user info

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

